package com.jrx.anytxn.transaction.job.interestFile.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.InterestFileConfig;
import com.jrx.anytxn.transaction.config.SftpConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;

@Configuration
@EnableConfigurationProperties({SftpConfig.class, InterestFileConfig.class})
public class InterestFileUploadConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(InterestFileUploadConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private SftpConfig sftpConfig;
    @Autowired
    private InterestFileConfig interestFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Bean
    public Job interestFileUploadJob() {
        return jobBuilderFactory.get("interestFileUploadJob")
                .start(interestFileUploadStep())
                .build();
    }

    @Bean
    public Step interestFileUploadStep() {
        return stepBuilderFactory.get("interestFileUploadStep")
                .tasklet(interestFileUploadTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet interestFileUploadTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("计提文件上传开始。。。。。。");

            String basePath = interestFileConfig.getInterestFilePath();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");

            String filePath = basePath + org.getTenantId() + File.separator + today + File.separator;

            File file = new File(filePath);
            File[] tempList = file.listFiles();
            if(tempList == null || tempList.length == 0){
                logger.error("文件上传，未获取到需要上传的文件");
                throw new RuntimeException("文件上传 ，未获取到需要上传的文件");
            }

            //1 获取连接
            SftpUtils.sftpConnect(sftpConfig.getUsername(),sftpConfig.getPassword(),sftpConfig.getHost(),sftpConfig.getPort());

            //2 检查创建目录
            String directory = sftpConfig.getUploadPath() + org.getTenantId() + "/" + today;
            SftpUtils.createDir(directory);

            //3 先上传TXT文件，再上传OK文件
            //原文件不删除，按照文件名判断是否需要上传
            String txtName = TransBizConstant.FILE_NAME_INTER + "_" +today + ".txt";
            for(File uploadFile : tempList){
                String filename = uploadFile.getName();
                if(txtName.equals(filename)){
                    SftpUtils.sftpUpload(uploadFile);
                }
            }
            logger.info("计提txt文件上传完成。。。。。。");

            String okFileName = TransBizConstant.FILE_NAME_INTER + "_" +today + ".ok";
            for(File uploadFile : tempList){
                String filename = uploadFile.getName();
                if(okFileName.equals(filename)){
                    SftpUtils.sftpUpload(uploadFile);
                }
            }
            logger.info("计提ok文件上传完成。。。。。。");

            //关闭连接
            SftpUtils.disSftpConnect();

            logger.info("计提文件上传结束。。。。。。");
            return RepeatStatus.FINISHED;
        };
    }
}
